import { useMemo, useState } from "react";
import { Menu, MenuS, NewBuild, Sort, BackGround } from "./styled";

import { iframeData } from "@/common/deskIframe.json";

import { TEXT_ICON_TYPE, FOLDER_ICON_TYPE, BLOG_ICON_TYPE } from "@/contains/iconTypeEnum"
import dataManager from "@/utils/dataManager";
import indexedDBManager from "@/utils/indexedDB";

const DeskMenu = ({ state, dispatch }) => {
  const { deskMenuX, deskMenuY, selectFid, folderData, folderList, menuType } =
    state;
  const [hoverType, setHoverType] = useState("");
  // 菜单事件处理
  const menuHandle = (e, type) => {
    e.preventDefault();
    e.stopPropagation();
    console.log(type);
    if (type === 1) return;
    switch (type) {
      case 2:
        break;
      default:
        break;
    }
  };

  const setBackGround = () => {
    dispatch({
      type: "setState",
      payload: {
        isShowBackGround: true,
      },
    });
  };

  const uploadBackGround = async () => {
    let file = document.createElement('input')
    const reader = new FileReader()
    file.type = 'file'
    file.accept = 'image/*'
    file.click()
    file.onchange = async (e) => {
      try {
        const currentUser = await dataManager.getCurrentUser();
        if (!currentUser) return;

        reader.readAsDataURL(e.target.files[0])
        reader.onload = async () => {
          const base64 = reader.result

          // 保存图片到IndexDB
          await indexedDBManager.saveImage({
            uid: currentUser.uid,
            name: 'background-' + Date.now(),
            data: base64,
            type: e.target.files[0].type,
            size: e.target.files[0].size
          });

          // 更新用户背景设置
          await dataManager.updateUser({ background: base64 });

          // 更新前端显示
          dispatch({
            type: "setState",
            payload: {
              backGroundUrl: base64,
            },
          });
        }
      } catch (error) {
        console.error('上传背景失败:', error);
      }
    }
  }

  const handleMouseLeave = () => {
    setHoverType("");
  };

  const newBuildSelect = (type) => {
    newBuildFolder(type);
  };

  // 新建文件夹
  const newBuildFolder = async (type) => {
    try {
      const currentUser = await dataManager.getCurrentUser();
      if (!currentUser) return;

      const folder = {
        uid: currentUser.uid,
        x: menuType === "desk" ? deskMenuX : -1, // 在文件夹的时候为desk
        y: menuType === "desk" ? deskMenuY : -1,
        name: "新建文件夹",
        iconType: type,
        iconUrl:  type === FOLDER_ICON_TYPE ? "/img/icon/folder.png" : "/img/icon/markdown.ico",
        fatherNode: selectFid,
        content: "",
      };

      if (menuType === "desk") {
        folderData.push(folder);
        dispatch({
          type: "setState",
          payload: {
            folderData,
            isRenameId: [folder.fid],
            isNewBuild: true,
          },
        });
      } else if (menuType === "explor") {
        folderList.push(folder);
        dispatch({
          type: "setState",
          payload: {
            folderList,
            isNewBuild: true,
            isRenameId: [folder.fid],
          },
        });
      }
    } catch (error) {
      console.error('新建文件夹失败:', error);
    }
  };

  const getHeight = useMemo(() => {
    if (menuType === "desk") {
      return 140;
    } else if (menuType === "explor") {
      return 70;
    } else {
      return 100;
    }
  }, [menuType]);

  const deskVisableMeunY = useMemo(() => {
    return deskMenuY + 140 >= window.innerHeight ? deskMenuY - 130 : deskMenuY
  }, [deskMenuY])

  // 排序文件夹
  const sortFolder = async (type) => {
    if (menuType === "desk") {
      deskFolderSort(type);
    } else if (menuType === "explor") {
      explorFolderSort(type);
    }
  };

  const explorFolderSort = async (type) => {
    console.log(folderList);
    if (folderList.length === 0) return;
    if (type === "name")
      folderList.sort((a, b) => a.name.charCodeAt() - b.name.charCodeAt());
    else if (type === "date") folderList.sort((a, b) => a.fid - b.fid);
    else {
    }
    // 前端更新
    dispatch({
      type: "setState",
      folderList,
    });
  };

  const deskFolderSort = async (type) => {
    try {
      const currentUser = await dataManager.getCurrentUser();
      if (!currentUser) return;

      const len = iframeData.length;
      if (folderData.length === len) {
        return;
      }
      const sortFolderData = folderData.slice(len);
      if (type === "name")
        sortFolderData.sort((a, b) => a.name.charCodeAt() - b.name.charCodeAt());
      else if (type === "date") sortFolderData.sort((a, b) => a.fid - b.fid);
      else {
      }

      let seeHeight = document.documentElement.clientHeight - 100;
      // 桌面排序逻辑
      let col = 1;
      let row = len + 1;
      for (let index = len; index < len + sortFolderData.length; index++) {
        if (index * 80 + 20 > seeHeight * col) {
          col++;
          row = 1;
        }
        sortFolderData[index - len].y = (row - 1) * 80 + 10;
        sortFolderData[index - len].x = 70 * (col - 1) + 10;
        row++;
      }

      // 前端更新
      dispatch({
        type: "setState",
        payload: {
          folderData: [...iframeData, ...sortFolderData],
        },
      });

      // 更新数据库中的位置信息
      for (const folder of sortFolderData) {
        await indexedDBManager.updateFolder(folder.fid, {
          x: folder.x,
          y: folder.y
        });
      }
    } catch (error) {
      console.error('桌面排序失败:', error);
    }
  };


  return (
    <MenuS deskMenuX={deskMenuX} deskMenuY={deskVisableMeunY}>
      <Menu height={getHeight}>
        <Menu.item
          onClick={(e) => menuHandle(e, 1)}
          onMouseMove={() => setHoverType("newBuild")}
          onMouseLeave={handleMouseLeave}
        >
          新建
        </Menu.item>
        <Menu.item
          onMouseMove={() => setHoverType("sort")}
          onMouseLeave={handleMouseLeave}
        >
          排序方式
        </Menu.item>
        {menuType === "desk" && (
          <Menu.item onClick={() => dispatch({ type: "deskRequest" })}>
            刷新
          </Menu.item>
        )}
        {menuType === "desk" && (
          <Menu.item
            onMouseMove={() => setHoverType("background")}
            onMouseLeave={handleMouseLeave}>设置/上传背景</Menu.item>
        )}
      </Menu>

      {hoverType === "newBuild" && (
        <NewBuild
          className="fadeIn"
          onMouseMove={() => setHoverType("newBuild")}
          onMouseLeave={handleMouseLeave}
        >
          <NewBuild.item onClick={() => newBuildSelect(FOLDER_ICON_TYPE)}>
            文件夹
          </NewBuild.item>
          <NewBuild.item onClick={() => newBuildSelect(BLOG_ICON_TYPE)}>
            博客文件
          </NewBuild.item>
          <NewBuild.item onClick={() => newBuildSelect(TEXT_ICON_TYPE)}>
            文本文档
          </NewBuild.item>
        </NewBuild>
      )}

      {hoverType === "background" && (
        <BackGround
          className="fadeIn"
          onMouseMove={() => setHoverType("background")}
          onMouseLeave={handleMouseLeave}
        >
          <BackGround.item onClick={setBackGround}>
            设置
          </BackGround.item>
          <BackGround.item onClick={uploadBackGround}>
            上传
          </BackGround.item>
        </BackGround>
      )}

      {hoverType === "sort" && (
        <Sort
          onMouseMove={() => setHoverType("sort")}
          onMouseLeave={handleMouseLeave}
        >
          <Sort.item onClick={() => sortFolder("name")}>名称</Sort.item>
          <Sort.item onClick={() => sortFolder("date")}>日期</Sort.item>
        </Sort>
      )}
    </MenuS>
  );
};

export default DeskMenu;
